/**
 * 侧边栏组件
 * 负责处理侧边栏交互、动态内容加载、分类列表、热门文章等功能
 */

class SidebarComponent {
    constructor() {
        this.sidebar = null;
        this.searchInput = null;
        this.categoriesList = null;
        this.popularPostsList = null;
        this.tagCloud = null;
        this.toggleButton = null;
        this.isMobile = false;
        this.isOpen = false;
    }

    /**
     * 初始化侧边栏组件
     */
    init() {
        this.sidebar = document.querySelector('.sidebar');
        this.searchInput = this.sidebar?.querySelector('.sidebar-search input');
        this.categoriesList = this.sidebar?.querySelector('.categories-list');
        this.popularPostsList = this.sidebar?.querySelector('.popular-posts-list');
        this.tagCloud = this.sidebar?.querySelector('.tag-cloud');
        this.toggleButton = document.querySelector('.sidebar-toggle');

        this.checkScreenSize();
        this.setupEventListeners();
        this.loadDynamicContent();
    }

    /**
     * 检查屏幕尺寸以确定是否为移动设备
     */
    checkScreenSize() {
        const handleResize = () => {
            this.isMobile = window.innerWidth < 768;
            
            // 在移动设备上默认隐藏侧边栏
            if (this.isMobile) {
                this.sidebar.classList.add('mobile');
                this.closeSidebar();
            } else {
                this.sidebar.classList.remove('mobile');
                this.openSidebar();
            }
        };

        // 初始检查
        handleResize();
        
        // 监听窗口大小变化
        window.addEventListener('resize', handleResize);
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 侧边栏切换按钮
        if (this.toggleButton) {
            this.toggleButton.addEventListener('click', () => {
                this.toggleSidebar();
            });
        }

        // 侧边栏背景点击关闭
        this.sidebar?.addEventListener('click', (e) => {
            if (this.isMobile && e.target === this.sidebar) {
                this.closeSidebar();
            }
        });

        // 搜索输入框事件
        if (this.searchInput) {
            this.searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.handleSearch();
                }
            });
        }

        // 分类链接点击事件
        const categoryLinks = this.categoriesList?.querySelectorAll('a');
        categoryLinks?.forEach(link => {
            link.addEventListener('click', (e) => {
                this.handleCategoryClick(e);
            });
        });

        // 标签云点击事件
        const tagLinks = this.tagCloud?.querySelectorAll('a');
        tagLinks?.forEach(link => {
            link.addEventListener('click', (e) => {
                this.handleTagClick(e);
            });
        });

        // ESC键关闭侧边栏
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isMobile && this.isOpen) {
                this.closeSidebar();
            }
        });
    }

    /**
     * 加载动态内容
     */
    async loadDynamicContent() {
        try {
            // 加载分类
            await this.loadCategories();
            
            // 加载热门文章
            await this.loadPopularPosts();
            
            // 加载标签云
            await this.loadTags();
        } catch (error) {
            console.error('Error loading sidebar content:', error);
            this.showErrorState();
        }
    }

    /**
     * 加载分类列表
     */
    async loadCategories() {
        if (!this.categoriesList) return;

        try {
            // 显示加载状态
            this.showLoadingState(this.categoriesList);

            // 使用API模块获取分类
            let categories = [];
            if (window.api && window.api.getCategories) {
                categories = await window.api.getCategories();
            } else {
                // 使用模拟数据
                categories = this.getMockCategories();
            }

            // 清空现有内容
            this.categoriesList.innerHTML = '';

            // 添加分类项
            categories.forEach(category => {
                const li = document.createElement('li');
                const a = document.createElement('a');
                
                a.href = `/?category=${encodeURIComponent(category.name)}`;
                a.textContent = category.name;
                
                // 添加文章计数
                const count = document.createElement('span');
                count.className = 'category-count';
                count.textContent = category.count;
                a.appendChild(count);
                
                li.appendChild(a);
                this.categoriesList.appendChild(li);
                
                // 绑定点击事件
                a.addEventListener('click', (e) => {
                    this.handleCategoryClick(e);
                });
            });
        } catch (error) {
            console.error('Error loading categories:', error);
            this.showErrorItem(this.categoriesList, '无法加载分类');
        }
    }

    /**
     * 加载热门文章
     */
    async loadPopularPosts() {
        if (!this.popularPostsList) return;

        try {
            // 显示加载状态
            this.showLoadingState(this.popularPostsList);

            // 使用API模块获取热门文章
            let popularPosts = [];
            if (window.api && window.api.getPopularPosts) {
                popularPosts = await window.api.getPopularPosts(5);
            } else {
                // 使用模拟数据
                popularPosts = this.getMockPopularPosts();
            }

            // 清空现有内容
            this.popularPostsList.innerHTML = '';

            // 添加热门文章项
            popularPosts.forEach(post => {
                const li = document.createElement('li');
                li.className = 'popular-post-item';
                
                // 文章链接容器
                const postLink = document.createElement('a');
                postLink.href = `/pages/post-template.html?id=${post.id}`;
                
                // 可选：添加缩略图
                if (post.image) {
                    const img = document.createElement('img');
                    img.src = post.image;
                    img.alt = post.title;
                    img.className = 'post-thumbnail';
                    postLink.appendChild(img);
                }
                
                // 文章信息
                const postInfo = document.createElement('div');
                postInfo.className = 'post-info';
                
                // 文章标题
                const title = document.createElement('h4');
                title.className = 'post-title';
                title.textContent = post.title;
                postInfo.appendChild(title);
                
                // 文章日期
                if (post.date) {
                    const date = document.createElement('span');
                    date.className = 'post-date';
                    date.textContent = this.formatDate(post.date);
                    postInfo.appendChild(date);
                }
                
                // 文章浏览量
                if (post.views !== undefined) {
                    const views = document.createElement('span');
                    views.className = 'post-views';
                    views.textContent = `${post.views} 阅读`;
                    postInfo.appendChild(views);
                }
                
                postLink.appendChild(postInfo);
                li.appendChild(postLink);
                this.popularPostsList.appendChild(li);
            });
        } catch (error) {
            console.error('Error loading popular posts:', error);
            this.showErrorItem(this.popularPostsList, '无法加载热门文章');
        }
    }

    /**
     * 加载标签云
     */
    async loadTags() {
        if (!this.tagCloud) return;

        try {
            // 显示加载状态
            this.showLoadingState(this.tagCloud);

            // 获取所有文章标签
            let tags = [];
            if (window.api && window.api.getPosts) {
                const posts = await window.api.getPosts();
                // 提取所有标签
                const allTags = posts.posts.flatMap(post => post.tags || []);
                // 统计标签频率
                const tagCounts = allTags.reduce((acc, tag) => {
                    acc[tag] = (acc[tag] || 0) + 1;
                    return acc;
                }, {});
                // 转换为数组
                tags = Object.entries(tagCounts).map(([name, count]) => ({ name, count }));
            } else {
                // 使用模拟数据
                tags = this.getMockTags();
            }

            // 清空现有内容
            this.tagCloud.innerHTML = '';

            // 添加标签
            tags.forEach(tag => {
                const a = document.createElement('a');
                a.href = `/?tag=${encodeURIComponent(tag.name)}`;
                a.textContent = tag.name;
                a.setAttribute('data-count', tag.count);
                
                // 根据标签频率设置不同的样式
                const sizeClass = this.getTagSizeClass(tag.count, tags);
                a.className = `tag ${sizeClass}`;
                
                this.tagCloud.appendChild(a);
                
                // 绑定点击事件
                a.addEventListener('click', (e) => {
                    this.handleTagClick(e);
                });
            });
        } catch (error) {
            console.error('Error loading tags:', error);
            this.showErrorItem(this.tagCloud, '无法加载标签');
        }
    }

    /**
     * 切换侧边栏显示/隐藏
     */
    toggleSidebar() {
        if (this.isOpen) {
            this.closeSidebar();
        } else {
            this.openSidebar();
        }
    }

    /**
     * 打开侧边栏
     */
    openSidebar() {
        if (!this.isMobile) return;
        
        this.isOpen = true;
        this.sidebar.classList.add('open');
        this.toggleButton.classList.add('active');
        document.body.classList.add('sidebar-open');
        
        // 防止背景滚动
        document.body.style.overflow = 'hidden';
        
        // 添加动画类
        setTimeout(() => {
            this.sidebar.classList.add('animated');
        }, 10);
    }

    /**
     * 关闭侧边栏
     */
    closeSidebar() {
        if (!this.isMobile) return;
        
        this.isOpen = false;
        this.sidebar.classList.remove('animated');
        this.toggleButton.classList.remove('active');
        document.body.classList.remove('sidebar-open');
        
        // 等待动画完成后移除open类
        setTimeout(() => {
            this.sidebar.classList.remove('open');
            
            // 恢复背景滚动
            document.body.style.overflow = '';
        }, 300);
    }

    /**
     * 处理搜索
     */
    handleSearch() {
        if (!this.searchInput) return;
        
        const searchTerm = this.searchInput.value.trim();
        
        if (searchTerm) {
            // 关闭侧边栏（如果打开）
            if (this.isOpen) {
                this.closeSidebar();
            }
            
            // 执行搜索
            console.log('侧边栏搜索:', searchTerm);
            
            // 使用路由或直接跳转
            if (window.router) {
                window.router.navigate(`/?search=${encodeURIComponent(searchTerm)}`);
            } else {
                window.location.href = `/?search=${encodeURIComponent(searchTerm)}`;
            }
        }
    }

    /**
     * 处理分类点击
     * @param {Event} e - 点击事件
     */
    handleCategoryClick(e) {
        e.preventDefault();
        const target = e.currentTarget;
        const category = target.textContent.trim().split(/\s+/)[0];
        
        // 关闭侧边栏
        if (this.isOpen) {
            this.closeSidebar();
        }
        
        // 导航到分类页面
        if (window.router) {
            window.router.navigate(`/?category=${encodeURIComponent(category)}`);
        } else {
            window.location.href = `/?category=${encodeURIComponent(category)}`;
        }
    }

    /**
     * 处理标签点击
     * @param {Event} e - 点击事件
     */
    handleTagClick(e) {
        e.preventDefault();
        const target = e.currentTarget;
        const tag = target.textContent.trim();
        
        // 关闭侧边栏
        if (this.isOpen) {
            this.closeSidebar();
        }
        
        // 导航到标签页面
        if (window.router) {
            window.router.navigate(`/?tag=${encodeURIComponent(tag)}`);
        } else {
            window.location.href = `/?tag=${encodeURIComponent(tag)}`;
        }
    }

    /**
     * 显示加载状态
     * @param {HTMLElement} container - 容器元素
     */
    showLoadingState(container) {
        container.innerHTML = '<div class="loading">加载中...</div>';
    }

    /**
     * 显示错误状态
     * @param {HTMLElement} container - 容器元素
     * @param {string} message - 错误消息
     */
    showErrorItem(container, message) {
        container.innerHTML = `<div class="error">${message}</div>`;
    }

    /**
     * 显示整体错误状态
     */
    showErrorState() {
        if (this.sidebar) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'sidebar-error';
            errorDiv.textContent = '加载侧边栏内容失败';
            
            // 添加到侧边栏顶部
            this.sidebar.prepend(errorDiv);
        }
    }

    /**
     * 格式化日期
     * @param {string} dateString - 日期字符串
     * @returns {string} 格式化后的日期
     */
    formatDate(dateString) {
        try {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        } catch (error) {
            return dateString;
        }
    }

    /**
     * 根据标签频率获取大小类
     * @param {number} count - 标签出现次数
     * @param {Array} allTags - 所有标签
     * @returns {string} 大小类名
     */
    getTagSizeClass(count, allTags) {
        // 找出最大和最小频率
        const counts = allTags.map(tag => tag.count);
        const maxCount = Math.max(...counts);
        const minCount = Math.min(...counts);
        const range = maxCount - minCount;
        
        if (range === 0) return 'tag-size-medium';
        
        // 计算频率百分比
        const percentage = (count - minCount) / range;
        
        if (percentage < 0.33) return 'tag-size-small';
        if (percentage < 0.66) return 'tag-size-medium';
        return 'tag-size-large';
    }

    // 模拟数据方法
    getMockCategories() {
        return [
            { name: 'JavaScript', count: 15 },
            { name: 'CSS', count: 12 },
            { name: 'Vue.js', count: 10 },
            { name: 'React', count: 8 },
            { name: '前端开发', count: 20 },
            { name: 'Node.js', count: 6 }
        ];
    }

    getMockPopularPosts() {
        return [
            {
                id: '101',
                title: '前端性能优化最佳实践',
                date: '2024-01-14',
                views: 3210,
                image: '../assets/images/performance.jpg'
            },
            {
                id: '102',
                title: 'React Hooks 完全指南',
                date: '2024-01-12',
                views: 2890,
                image: '../assets/images/react-hooks.jpg'
            },
            {
                id: '103',
                title: 'TypeScript 实用技巧',
                date: '2024-01-08',
                views: 1980,
                image: '../assets/images/typescript.jpg'
            },
            {
                id: '104',
                title: 'CSS Grid 布局实战',
                date: '2024-01-05',
                views: 1560,
                image: '../assets/images/css-grid.jpg'
            },
            {
                id: '105',
                title: 'Vue 3 Composition API 详解',
                date: '2024-01-01',
                views: 1320,
                image: '../assets/images/vue3.jpg'
            }
        ];
    }

    getMockTags() {
        return [
            { name: 'JavaScript', count: 25 },
            { name: 'ES6', count: 18 },
            { name: 'Vue', count: 15 },
            { name: 'React', count: 12 },
            { name: 'CSS', count: 20 },
            { name: 'TypeScript', count: 10 },
            { name: 'Node.js', count: 8 },
            { name: 'Webpack', count: 6 },
            { name: '性能优化', count: 14 },
            { name: '响应式设计', count: 16 },
            { name: '前端架构', count: 9 },
            { name: 'UI/UX', count: 11 }
        ];
    }

    /**
     * 销毁组件，清理事件监听器
     */
    destroy() {
        // 清理事件监听器
        if (this.toggleButton) {
            this.toggleButton.removeEventListener('click', this.toggleSidebar.bind(this));
        }

        if (this.searchInput) {
            this.searchInput.removeEventListener('keypress', this.handleSearch.bind(this));
        }

        // 移除document事件监听器
        document.removeEventListener('keydown', () => {});
        
        // 移除窗口大小变化监听器
        window.removeEventListener('resize', () => {});
    }
}

// 导出组件类
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = SidebarComponent;
} else {
    window.SidebarComponent = SidebarComponent;
}

/**
 * 使用示例：
 * 
 * // 在页面加载完成后初始化
 * document.addEventListener('DOMContentLoaded', () => {
 *   const sidebar = new SidebarComponent();
 *   sidebar.init();
 * });
 */